package com.enzoism.springboot.dive.dao;

import com.enzoism.springboot.dive.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
@Repository
public class UserDao {
    
    // 使用ConcurrentHashMap模拟数据库，以复合key作为键
    private final Map<String, User> database = new ConcurrentHashMap<>();
    
    // 初始化一些测试数据
    public UserDao() {
        // 初始化测试数据
        User user1 = new User(1L, 1L, "admin", "admin@example.com", "13800138000", 1, "2024-01-01");
        User user2 = new User(2L, 2L, "user", "user@example.com", "13900139000", 1, "2024-01-02");
        User user3 = new User(3L, 1L, "manager", "manager@example.com", "13700137000", 1, "2024-01-03");
        
        database.put(user1.getCompositeKey(), user1);
        database.put(user2.getCompositeKey(), user2);
        database.put(user3.getCompositeKey(), user3);
        
        log.info("初始化用户数据完成，共{}条记录", database.size());
    }
    
    /**
     * 新增用户
     */
    public User insert(User user) {
        String key = user.getCompositeKey();
        if (database.containsKey(key)) {
            throw new RuntimeException("用户已存在，userId: " + user.getUserId() + ", roleId: " + user.getRoleId());
        }
        database.put(key, user);
        log.info("新增用户成功：{}", user);
        return user;
    }
    
    /**
     * 根据复合key查询用户
     */
    public User selectByCompositeKey(Long userId, Long roleId) {
        String key = userId + "_" + roleId;
        User user = database.get(key);
        log.info("查询用户：userId={}, roleId={}, 结果：{}", userId, roleId, user != null ? "存在" : "不存在");
        return user;
    }
    
    /**
     * 查询所有用户
     */
    public List<User> selectAll() {
        List<User> users = new ArrayList<>(database.values());
        log.info("查询所有用户，共{}条记录", users.size());
        return users;
    }
    
    /**
     * 根据userId查询用户列表（一个userId可能有多个roleId）
     */
    public List<User> selectByUserId(Long userId) {
        List<User> users = database.values().stream()
                .filter(user -> user.getUserId().equals(userId))
                .collect(Collectors.toList());
        log.info("根据userId查询用户：userId={}, 结果数量：{}", userId, users.size());
        return users;
    }
    
    /**
     * 根据roleId查询用户列表
     */
    public List<User> selectByRoleId(Long roleId) {
        List<User> users = database.values().stream()
                .filter(user -> user.getRoleId().equals(roleId))
                .collect(Collectors.toList());
        log.info("根据roleId查询用户：roleId={}, 结果数量：{}", roleId, users.size());
        return users;
    }
    
    /**
     * 更新用户
     */
    public User update(User user) {
        String key = user.getCompositeKey();
        if (!database.containsKey(key)) {
            throw new RuntimeException("用户不存在，userId: " + user.getUserId() + ", roleId: " + user.getRoleId());
        }
        database.put(key, user);
        log.info("更新用户成功：{}", user);
        return user;
    }
    
    /**
     * 删除用户
     */
    public boolean delete(Long userId, Long roleId) {
        String key = userId + "_" + roleId;
        User removed = database.remove(key);
        boolean success = removed != null;
        log.info("删除用户：userId={}, roleId={}, 结果：{}", userId, roleId, success ? "成功" : "失败");
        return success;
    }
    
    /**
     * 判断用户是否存在
     */
    public boolean exists(Long userId, Long roleId) {
        String key = userId + "_" + roleId;
        boolean exists = database.containsKey(key);
        log.info("判断用户是否存在：userId={}, roleId={}, 结果：{}", userId, roleId, exists ? "存在" : "不存在");
        return exists;
    }
    
    /**
     * 获取数据库大小（用于测试）
     */
    public int getDatabaseSize() {
        return database.size();
    }
}